const config=require('./config')
const session = require('koa-session');
const RedisStore = require('koa2-session-redis');
const Koa = require('koa')
const locale = require('koa-locale')
const i18n = require('koa-i18n')
const views = require('koa-views')
const koaStatic = require('koa-static')
const path = require('path')
const port = process.env.PORT || 1001
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const app = new Koa()
const ejs = require('ejs')
const routes = require('./hyperplay/routes')
const cors = require('koa2-cors')
const api = require('./api')

locale(app)

// 配置i18n
app.use(i18n(app, {
    directory: path.join(__dirname,'./hyperplay/locales'),
    locales: ['en_US','zh_CN','zh_TW'], 
    modes:[function(){
        if(!this.cookies.get('lang')){
            this.cookies.set('lang','zh_CN',{
                httpOnly: false,  // 是否只用于http请求中获取
                overwrite: false  // 是否允许重写
            })
        }
        if(this.cookies.get('lang')&&this.cookies.get('lang')=='en_US'){
            return 'en_US';
        }
        else if(this.cookies.get('lang')&&this.cookies.get('lang')=='zh_TW'){
            return 'zh_TW';
        }else{
            return 'zh_CN';
        }
    }]
}))


//
const redis_conf = {
    key: 'Porschev',
    maxAge: 7200000,
    overwrite: true,
    httpOnly: true,
    rolling: false,
    sign: false,
    store: new RedisStore({
        host: config.redis.host,
        port:  config.redis.port,
    })
};
app.keys = [ 'foo' ];
app.use(session(redis_conf, app));


//请求数据获取
app.use(bodyparser({
    enableTypes:['json', 'form', 'text']
}))

//日志插件
app.use(logger())

// 配置静态资源加载中间件
app.use(koaStatic(
    path.join(__dirname , './hyperplay/static')
))

// 配置服务端模板渲染引擎中间件
app.use(views(path.join(__dirname, './hyperplay/views'), {
    extension: 'ejs',
    map: { html: 'ejs' }
}))
app.use(require('./middleware/routeFilter'))

// 初始化路由中间件
app.use(routes.routes(), routes.allowedMethods())

// CORS
app.use(cors({
    //请求拦截器
    origin: function (ctx) {
        return ctx.request.header.origin // 只允许
    },
    credentials: true,
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept']
}))
app.use(require('./middleware/response'))


//请求接口
app.use(api())

app.listen(port, () => {
    console.log(`listen ${port} port`)
})
